<?php

namespace app\modules\product\controllers;

use app\controllers\BaseController;
use app\services\Demand;
use app\services\File;
use app\services\Product;
use app\services\User;
use app\utils\Utils;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;


class DemandController extends BaseController
{
    public function actionList($data = 0)
    {
        if (!$data) {
            return $this->render('list');
        }

        $request = Yii::$app->request;
        $post = Yii::$app->request->post();
        $get = Yii::$app->request->get();

        $where[] = ['demand.status' => 10];
        $where[] = ['demand.product_id' => Product::authProductId()]; //获取拥有需求组成员的需求,超管获取全部
        if ($get['product_id']) {
            $where[] = ['demand.product_id' => $get['product_id']]; //筛选单个产品
        }
        switch ($get['search_type']) {
            case 1: //所有
                break;
            case 2: //未完成
                $where[] = ['<>', 'demand.step', 3];
                break;
            case 3: //指给我
                $where[] = ['demand.develop_user_id' => Yii::$app->user->identity->id];
                break;
            case 4: //指给我未完成
                $where[] = ['<>', 'demand.step', 3];
                $where[] = ['demand.develop_user_id' => Yii::$app->user->identity->id];
                break;
            case 5: //我创建
                $where[] = ['demand.created_by' => Yii::$app->user->identity->id];
                break;
            case 6: //我创建未完成
                $where[] = ['<>', 'demand.step', 3];
                $where[] = ['demand.created_by' => Yii::$app->user->identity->id];
                break;
            case 7: //已完成
                $where[] = ['demand.step' => 3];
                break;
        }

        if ($search = Utils::formUnserialize(Yii::$app->request->post('searchData'))) {
            foreach ($search as $k => $v) {
                if ($v === '') {
                    continue;
                }
                switch ($k) {
                    case 'order_no':
                        $where[] = ['demand.id' => Utils::getNumeric($v, 'DEMD')];
                        break;
                    case 'title':
                        $where[] = ['like', 'demand.title', $v];
                        break;
                    case 'create_user':
                        $user = User::find()->where(['or', ['like', 'username', $v], ['like', 'realname', $v]])->one();
                        $where[] = $where[] = ['demand.created_by' => $user ? $user->id : 0];
                        break;
                    case 'develop_user':
                        $user = User::find()->where(['or', ['like', 'username', $v], ['like', 'realname', $v]])->one();
                        $where[] = $where[] = ['demand.develop_user_id' => $user ? $user->id : 0];
                        break;
                    case 'step':
                        $where[] = ['demand.step' => $v];
                        break;
                }
            }
        }

        $result = Demand::listPage($where, 'demand.*', 'demand.id desc', $request->post('page', 1), $request->post('limit', 10), ['product']);
        $return = ArrayHelper::toArray($result);

        foreach ($result['data'] as $key => $val) {
            $return['data'][$key]['order_no'] = Utils::generateOrderNo('DEMD', $val->id);
            $return['data'][$key]['product_title'] = $val->product ? $val->product->title : '';
            $return['data'][$key]['create_user'] = $val->createUser ? $val->createUser->name : '';
            $return['data'][$key]['develop_user'] = $val->developUser ? $val->developUser->name : '未指派';
            $return['data'][$key]['created_at'] = date('Y-m-d H:i:s', $val->created_at);
            $return['data'][$key]['plan_start_date'] = $val->plan_start_date ? date('Y-m-d H:i:s', $val->plan_start_date) : '';
            $return['data'][$key]['plan_end_date'] = $val->plan_end_date ? date('Y-m-d H:i:s', $val->plan_end_date) : '';
            $return['data'][$key]['step'] = $val::getStep()[$val->step];
            $return['data'][$key]['step_code'] = $val->step;
            $return['data'][$key]['canEdit'] = $val->canEdit();
            $return['data'][$key]['canDel'] = $val->canDel();
        }
        return $this->asJson($return);
    }

    public function actionCreate()
    {
        $request = Yii::$app->request;
        $post = $request->post();

        if ($request->isPost) {
            $model = new Demand();
            $model->load($post, '');
            $model->plan_start_date = $post['plan_start_date'] ? strtotime($post['plan_start_date']) : 0;
            $model->plan_end_date = $post['plan_end_date'] ? strtotime($post['plan_end_date']) : 0;
            if ($model->develop_user_id) $model->step = 1;

            if ($model->save()) {
                if (isset($post['attachment'])) File::batchSave($post['attachment'], 'demand', $model->id);
                $model->sendEmail();
                $model->operation_log->create($this, "创建了需求 {$model->title}", Url::to(['view', 'id' => $model->id]), true);
                if ($model->develop_user_id) $model->operation_log->create($this, "指派了需求 {$model->title} 给 {$model->developUser->name}", Url::to(['view', 'id' => $model->id]), true);
                return $this->success([], '创建成功');
            }
            return $this->error($model->errors);
        }

        return $this->render('create');
    }

    public function actionUpdate($id)
    {
        $request = Yii::$app->request;
        $post = $request->post();

        if ($request->isPost) {
            $model = Demand::findOne(['id' => $post['id'], 'status' => 10]);
            $model->load($post, '');
            $model->plan_start_date = $post['plan_start_date'] ? strtotime($post['plan_start_date']) : 0;
            $model->plan_end_date = $post['plan_end_date'] ? strtotime($post['plan_end_date']) : 0;
            if ($model->develop_user_id != $model->getOldAttribute('develop_user_id')) {
                $model->step = 1;
                $set_develop_user = true;
            }

            if ($model->save()) {
                if (isset($post['attachment'])) File::batchSave($post['attachment'], 'demand', $model->id);
                if (isset($post['attachment_remove'])) File::batchRemove($post['attachment_remove']);
                $model->operation_log->create($this, "编辑了需求 {$model->title}", Url::to(['view', 'id' => $model->id]), true);
                if (isset($set_develop_user) && $set_develop_user) {
                    $model->sendEmail();
                    $model->operation_log->create($this, "指派了需求 {$model->title} 给 {$model->developUser->name}", Url::to(['view', 'id' => $model->id]), true);
                }
                return $this->success([], '编辑成功');
            }
            return $this->error($model->errors);
        }

        if (!$model = Demand::findOne(['id' => $id, 'status' => [10, 20]])) {
            return $this->alert('未找到该需求');
        }
        if (!$model->canEdit()) {
            return $this->alert('反正不是我的 我也不该要~~');
        }

        return $this->render('update', ['model' => $model]);
    }

    public function actionView($id)
    {
        if (!$model = Demand::findOne(['id' => $id, 'status' => 10])) {
            return $this->alert('未找到该需求');
        }

        return $this->render('view', ['model' => $model]);
    }

    public function actionDelete($id)
    {
        if (!$model = Demand::findOne(['id' => $id, 'status' => [10]])) {
            return $this->error('未找到该需求');
        }
        if (!$model->canDel()) {
            return $this->error('反正不是我的 我也不该要~~');
        }
        $model->status = 0;
        $model->save();
        $model->operation_log->create($this, "删除了需求 {$model->title}", '', true);
        return $this->success([], '删除成功');
    }

    /**
     * 需求指派
     * @method actionSetDevelopUser
     * @return \yii\web\Response
     * @author ZhangYuan 574368565@qq.com
     * @time 2021/1/28 8:45
     */
    public function actionSetDevelopUser()
    {
        $request = Yii::$app->request;
        $post = $request->post();

        $demand_id = $post['demand_id'];
        $checked = $post['checked'];

        if (!$demand = Demand::findOne(['id' => $demand_id, 'status' => 10])) {
            return $this->error('未找到该需求');
        }

        if ($demand->step == 3) {
            return $this->error('需求已完成不能改派');
        }

        if (!$demand->canEdit()) {
            return $this->error('反正不是我的 我也不该要~~');
        }

        $demand->develop_user_id = $checked[0]['id'];
        $demand->step = 1;

        if (!$demand->save()) return $this->error($demand->errors);
        $demand->sendEmail();
        $demand->operation_log->create($this, "指派了需求 {$demand->title} 给 {$demand->developUser->name}", Url::to(['view', 'id' => $demand->id]), true);
        return $this->success([], '需求指派成功');
    }

    /**
     * 切换需求状态
     * @method actionSwitchStep
     * @param $demand_id
     * @return \yii\web\Response
     * @author ZhangYuan 574368565@qq.com
     * @time 2021/1/28 8:45
     */
    public function actionSwitchStep($demand_id)
    {
        if (!$demand = Demand::findOne(['id' => $demand_id, 'status' => 10])) {
            return $this->error('未找到该需求');
        }

        $demand->step = $demand->step + 1;
        $demand->save();
        $demand->operation_log->create($this, "更新了需求 {$demand->title} 进度为 {$demand::getStep()[$demand->step]}", Url::to(['view', 'id' => $demand->id]), true);
        //完成需求后扣除产品的工期
        if ($demand->step == 3) {
            $product = $demand->product;
            $product->duration_used = $product->duration_used + $demand->period;
            $product->save();
        }
        return $this->success([], '操作成功');
    }
}
